package com.bootlever.framework.rmi.proxy;

import com.bootlever.framework.rmi.templates.RmiTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class RmiProxy implements InvocationHandler {

    private static final Logger logger = LoggerFactory.getLogger(RmiProxy.class);

    private Class<?> interfaceClass;
    private Object proxyObject;
    private ApplicationContext applicationContext;
    private RmiTemplate rmiTemplate;

    public RmiProxy() {
    }

    public RmiProxy(Class interfaceClass){
        this.interfaceClass = interfaceClass;
    }



    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        logger.info("proxy调用Rmi方法{}()", method.getName());
        this.rmiTemplate = applicationContext.getBean(RmiTemplate.class);
        if (rmiTemplate !=null) {
            Object obj = rmiTemplate.get(interfaceClass);
            return method.invoke(obj, args);
        }
        return "";
    }


    public Object initRmiClient(){
        logger.info("proxy initRmiClient被调用....");
        return null;
    }

    public Class<?> getInterfaceClass() {
        return interfaceClass;
    }

    public void setInterfaceClass(Class<?> interfaceClass) {
        this.interfaceClass = interfaceClass;
    }

    public Object getProxyObject() {
        return proxyObject;
    }

    public void setProxyObject(Object proxyObject) {
        this.proxyObject = proxyObject;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public RmiTemplate getRmiTemplate() {
        return rmiTemplate;
    }

    public void setRmiTemplate(RmiTemplate rmiTemplate) {
        this.rmiTemplate = rmiTemplate;
    }

    public Object bind(Class<?> cls, ApplicationContext applicationContext) {
        this.interfaceClass = cls;
        this.applicationContext = applicationContext;
        return Proxy.newProxyInstance(cls.getClassLoader(), new Class[] {interfaceClass}, this);
    }

}
